import { RequestOptions } from 'https';
import { ProxyOptions } from '../index';

export default function proxy({ req, proxyTable = [], https, host, port }: ProxyOptions) {
	const reqUrl = req.url as string;

	const reqOption: RequestOptions = {
		protocol: https ? 'https:' : 'http:',
		hostname: host,
		port: port,
		path: reqUrl,
		method: req.method,
		headers: req.headers,
		rejectUnauthorized: false,
	};

	proxyTable.some((opt) => {
		const matchReg = new RegExp(opt.match);
		if (matchReg.test(reqUrl)) {
			reqOption.protocol = opt.target.match(/https?:/)?.[0] || 'http:';
			reqOption.hostname = opt.target.match(/[^(https?:\/\/)]([^:]+)/)?.[0];
			reqOption.port = Number(opt.target.match(/:([0-9]+)/)?.[1]) || undefined;
			reqOption.headers!.host = [reqOption.hostname, reqOption.port].filter((i) => i).join(':');

			if (opt.rewrite) {
				Object.keys(opt.rewrite).forEach((reg) => {
					if (typeof opt.rewrite![reg] === 'string') {
						reqOption.path = reqOption.path?.replace(new RegExp(reg), opt.rewrite![reg]);
					}
					if (typeof opt.rewrite![reg] === 'function') {
						const pathMatchArray = reqOption.path?.match(new RegExp(reg));
						if (pathMatchArray) {
							const replaceStr = opt.rewrite![reg](pathMatchArray);
							reqOption.path = reqOption.path?.replace(new RegExp(reg), replaceStr);
						}
					}
				});
			}

			if (opt.local) {
				reqOption.host = 'local';
				reqOption.port = 'local';
			}

			return true;
		}
		return false;
	});

	return reqOption;
}
